package com.mvc.tx;

import com.mvc.annotion.Resource;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @ Author xsd
 * @ crate time 2020/6/5 17:01
 * @ 描述
 */
//@Component
public class ProxyFactoryImpl implements ProxyFactory {
    @Resource
    private TransactionManager transactionManager;
    @Override
    public Object getJdkProxy(Object obj) {
        // implements InvocationHandler 匿名内部类处理。
        // Person proxy = (Person) Proxy.newProxyInstance(loader,interfaces, handler);
        return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Object result=null;
                try{
                    transactionManager.beginTransaction();
                    result = method.invoke(obj, args);
                    transactionManager.commit();
                }catch (Exception e){
                    transactionManager.rollback();
                    throw e;
                }
                return result;
            }
        });
    }

    @Override
    public Object getCglibProxy(Object obj) {
        return null;
    }
}
